package com.liezh.eventbus.infrastructure.bus.command;

import org.springframework.context.ApplicationContext;
import com.liezh.eventbus.domain.Service;
import com.liezh.eventbus.domain.bus.command.Command;
import com.liezh.eventbus.domain.bus.command.CommandBus;
import com.liezh.eventbus.domain.bus.command.CommandHandler;
import com.liezh.eventbus.domain.bus.command.CommandHandlerExecutionError;

/**
 * TODO
 * 中介人，持有所有的CommandBus
 * 具体做事件处理的是具体的CommandBus
 *
 * 也是事件分发器
 */
@Service
public final class InMemoryCommandBus implements CommandBus {
    //
    private final CommandHandlersInformation information;
    private final ApplicationContext         context;

    public InMemoryCommandBus(CommandHandlersInformation information, ApplicationContext context) {
        this.information = information;
        this.context     = context;
    }

    @Override
    public void dispatch(Command command) throws CommandHandlerExecutionError {
        try {
            Class<? extends CommandHandler> commandHandlerClass = information.search(command.getClass());

            CommandHandler handler = context.getBean(commandHandlerClass);
            //TODO 事件分发
            handler.handle(command);
        } catch (Throwable error) {
            throw new CommandHandlerExecutionError(error);
        }
    }
}
